// $codepro.audit.disable importStyle, numericLiterals
/**
 * Class: Patient Information Panel
 * Description: 
 * 
 * @author Team Awesome Express
 * @version $ Revision 1.0 $
 * 
 */

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;


import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JButton;
import java.awt.Font;

import java.awt.GradientPaint;

import javax.swing.JSeparator;
import javax.swing.SwingConstants;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.swing.JScrollPane;
import javax.swing.JList;

//import org.jfree.chart.*;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.axis.DateAxis;


import org.jfree.chart.plot.XYPlot;


import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;



import javax.swing.ButtonGroup;


/**
 * @author Team Awesome Express
 * @version 1.0
 */
public class PatientInformationPanel extends JPanel {
	/**
	 * Field txtInsurance.
	 */
	private final JTextField txtInsurance;
	
	private  ChartPanel chartPanel;

	/**
	 * Field txtAllergies.
	 */
	private final JTextField txtAllergies;

	/**
	 * Field txtPharmacy.
	 */
	private final JTextField txtPharmacy;

	/**
	 * Field txtEmail.
	 */
	private final JTextField txtEmail;

	/**
	 * Field txtFirstName.
	 */
	private final JTextField txtFirstName;

	/**
	 * Field txtAddress.
	 */
	private final JTextField txtAddress;

	/**
	 * Field txtPhoneNum.
	 */
	private final JTextField txtPhoneNum;

	/**
	 * Field txtUserID.
	 */
	private final JTextField txtUserID;

	final JScrollPane scrollPane_1;
	
	/**
	 * Field txtSocialNum.
	 */
	private final JTextField txtSocialNum;

	/**
	 * Field txtAge.
	 */
	private final JTextField txtAge;

	/**
	 * Field txtLastName.
	 */
	private final JTextField txtLastName;

	/**
	 * Field myDataManager.
	 */
	private final DataManager myDataManager;

	/**
	 * Field treatmentList.
	 */
	private JList treatmentList;

	/**
	 * Field treatmentRows.
	 */
	private final int treatmentRows[];

	/**
	 * Field treatRecord.
	 */
	private CreateTreatmentRecord treatRecord;

	/**
	 * Field patientInvoice.
	 */
	private PatientInvoice patientInvoice;

	/**
	 * Field treatmentArray.
	 */
	private TreatmentRecord[] treatmentArray;

	/**
	 * Field patientRowNum.
	 */
	private final int patientRowNum[];

	/**
	 * Field gender.
	 */
	private String gender;

	/**
	 * Field p.
	 */
	private final Person person1;

	/**
	 * Field frame.
	 */
	private static JFrame Frame;

	/**
	 * Field treatmentArrayList.
	 */
	private ArrayList treatmentArrayList = new ArrayList();

	/**
	 * Field buttonGroup.
	 */
	private final ButtonGroup buttonGroup = new ButtonGroup();
	
	/**
	 * Field myThreadPool.
	 */
	private static ExecutorService MyThreadPool = Executors.newCachedThreadPool();

	/**
	 * Create the panel.
	 * @param dataManager DataManager
	 * @param p Patient
	 */
	public PatientInformationPanel(DataManager dataManager, Patient p) {
		
		setBackground(GlobalVars.BACKGROUND);
		myDataManager = dataManager;
		this.person1 = p;
		treatmentRows = myDataManager.getRowNumbers(GlobalVars.TREATMENT_RECORD_SHEET, 1, p.getLoginName()); // treatmentRows now contains the rows 
		patientRowNum = myDataManager.getRowNumbers(GlobalVars.PATIENT_SHEET, 1, p.getLoginName());
		TreatmentRecord[] tempArray = new TreatmentRecord[1];
		//tempArray[0]= new TreatmentRecord("Test");
		//tempArray[0].creationDate="Loading Treatment Record List";
		treatmentArray = tempArray; //getTreatmentRecords(treatmentRows);
		
			
		setLayout(null);
		
		final JLabel lblUserID = new JLabel("UserID :");
		lblUserID.setBounds(10, 49, 73, 14);
		add(lblUserID);
		
		final JLabel lblGender = new JLabel("Gender :");
		lblGender.setBounds(10, 256, 58, 14);
		add(lblGender);
		
		final JLabel lblSocialNum = new JLabel("Social Security # :");
		lblSocialNum.setBounds(10, 320, 113, 14);
		add(lblSocialNum);
		
		final JLabel lblAddress = new JLabel("Address :");
		lblAddress.setBounds(10, 153, 73, 14);
		add(lblAddress);
		
		final JLabel lblFirstNme = new JLabel("First Name :");
		lblFirstNme.setBounds(10, 88, 73, 14);
		add(lblFirstNme);
		
		final JLabel lblPhoneNum = new JLabel("Phone Number :");
		lblPhoneNum.setBounds(10, 185, 106, 14);
		add(lblPhoneNum);
		
		final JLabel lblEmail = new JLabel("Email Address :");
		lblEmail.setBounds(10, 220, 106, 14);
		add(lblEmail);
		
		final JLabel lblAllergies = new JLabel("Allergies :");
		lblAllergies.setBounds(10, 476, 77, 14);
		add(lblAllergies);
		
		final JLabel lblPharmacy = new JLabel("Pharmacy :");
		lblPharmacy.setBounds(10, 398, 77, 14);
		add(lblPharmacy);
		
		final JLabel lblInsurance = new JLabel("Insurance :");
		lblInsurance.setBounds(10, 435, 77, 17);
		add(lblInsurance);
		
		txtInsurance = new JTextField();
		txtInsurance.setColumns(10);
		txtInsurance.setBounds(126, 432, 179, 20);
		add(txtInsurance);
		
		txtAllergies = new JTextField();
		txtAllergies.setColumns(10);
		txtAllergies.setBounds(126, 473, 179, 20);
		add(txtAllergies);
		
		txtPharmacy = new JTextField();
		txtPharmacy.setColumns(10);
		txtPharmacy.setBounds(126, 395, 179, 20);
		add(txtPharmacy);
		
		txtEmail = new JTextField();
		txtEmail.setColumns(10);
		txtEmail.setBounds(126, 217, 179, 20);
		add(txtEmail);
		
		txtFirstName = new JTextField();
		txtFirstName.setColumns(10);
		txtFirstName.setBounds(129, 85, 106, 20);
		add(txtFirstName);
		
		txtAddress = new JTextField();
		txtAddress.setColumns(10);
		txtAddress.setBounds(129, 150, 325, 20);
		add(txtAddress);
		
		txtPhoneNum = new JTextField();
		txtPhoneNum.setColumns(10);
		txtPhoneNum.setBounds(128, 182, 102, 20);
		add(txtPhoneNum);
		
		txtUserID = new JTextField();
		txtUserID.setColumns(10);
		txtUserID.setBounds(129, 46, 106, 20);
		add(txtUserID);
		
		final JRadioButton femaleRadioButton = new JRadioButton("Female");
		buttonGroup.add(femaleRadioButton);
		femaleRadioButton.setBounds(109, 251, 78, 23);
		add(femaleRadioButton);
		
		final JRadioButton maleRadioButton = new JRadioButton("Male");
		buttonGroup.add(maleRadioButton);
		maleRadioButton.setBounds(199, 251, 77, 23);
		add(maleRadioButton);
		
		final JLabel lblLastName = new JLabel("Last Name :");
		lblLastName.setBounds(10, 122, 73, 14);
		add(lblLastName);
		
		txtSocialNum = new JTextField();
		txtSocialNum.setColumns(10);
		txtSocialNum.setBounds(128, 317, 102, 20);
		add(txtSocialNum);
		
		final JLabel lblAge = new JLabel("Age :");
		lblAge.setBounds(10, 284, 58, 14);
		add(lblAge);
		
		txtAge = new JTextField();
		txtAge.setColumns(10);
		txtAge.setBounds(97, 282, 102, 20);
		add(txtAge);
		
		txtLastName = new JTextField();
		txtLastName.setColumns(10);
		txtLastName.setBounds(129, 117, 106, 20);
		add(txtLastName);
		
		final JButton saveButton = new JButton("Save");
		saveButton.addMouseListener(new MouseAdapter() {

			public void mousePressed(MouseEvent e) {
				savePressed();
			}
		});
		saveButton.setBounds(54, 534, 100, 23);
		add(saveButton);
		
		final JButton cancelButton = new JButton("Cancel");
		cancelButton.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent arg0) {
				Frame.dispose();
			}
		});
		cancelButton.setBounds(177, 534, 113, 23);
		add(cancelButton);
		
		final JLabel lblPersonalInformation = new JLabel("Personal Information");
		lblPersonalInformation.setFont(new Font("Tahoma", Font.BOLD, 11));
		lblPersonalInformation.setBounds(54, 11, 137, 14);
		add(lblPersonalInformation);
		
		final JLabel lblMedicalInformation = new JLabel("Medical Information");
		lblMedicalInformation.setFont(new Font("Tahoma", Font.BOLD, 11));
		lblMedicalInformation.setBounds(54, 356, 137, 14);
		add(lblMedicalInformation);
		
		final JLabel lblNewLabel = new JLabel("Medical History");
		lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 11));
		lblNewLabel.setBounds(703, 11, 149, 14);
		add(lblNewLabel);
		
		final JSeparator separator1 = new JSeparator();
		separator1.setOrientation(SwingConstants.VERTICAL);
		separator1.setBounds(479, 0, 15, 568);
		add(separator1);
		
		final JSeparator separator = new JSeparator();
		separator.setOrientation(SwingConstants.VERTICAL);
		separator.setBounds(493, 0, 47, 568);
		add(separator);
		
		scrollPane_1 = new JScrollPane();
		scrollPane_1.setBounds(519, 49, 484, 201);
		add(scrollPane_1);
				
		
		final JLabel lblPatientHealthHistory = new JLabel("Patient Health History");
		lblPatientHealthHistory.setFont(new Font("Tahoma", Font.BOLD, 11));
		lblPatientHealthHistory.setBounds(682, 323, 170, 14);
		add(lblPatientHealthHistory);
		

		
		if (dataManager.getUserType() == GlobalVars.PATIENT_USERTYPE) { // Panel is opened by a patient
			saveButton.setVisible(false); // Hide the save button
			txtInsurance.setEnabled(false);
			txtAllergies.setEnabled(false);
			txtPharmacy.setEnabled(false);
			txtEmail.setEnabled(false);
			txtFirstName.setEnabled(false);
			txtAddress.setEnabled(false);
			txtPhoneNum.setEnabled(false);
			txtUserID.setEnabled(false);
			txtSocialNum.setEnabled(false);
			txtAge.setEnabled(false);
			txtLastName.setEnabled(false);
			maleRadioButton.setEnabled(false);
			femaleRadioButton.setEnabled(false);
			
		}
			
		txtUserID.setText(p.getLoginName());
		txtAllergies.setText(p.getAllergies());
		txtPharmacy.setText(p.getPharmacy());
		txtEmail.setText(p.getEmail());
		txtPhoneNum.setText(p.getPhoneNum());
		txtFirstName.setText(p.getName());
		txtLastName.setText(p.getLastname());
		txtInsurance.setText(p.getInsurance());
		txtSocialNum.setText(p.getSocialSecNum());
		txtAge.setText(p.getAge());
		txtAddress.setText(p.getAddress());
		
		final JButton btnViewInvoice = new JButton("View Invoice");
		btnViewInvoice.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) { // Code for when the View Invoice button is pressed
				final int index = treatmentList.getSelectedIndex();
				patientInvoice = new PatientInvoice(treatmentArray[index]); // Create a patientInvoice for that specific clicked treatment record
				PatientInvoicePanel.createWindow(myDataManager, patientInvoice); // $codepro.audit.disable com.instantiations.assist.eclipse.analysis.unusedReturnValue
			}
		});
		btnViewInvoice.setBounds(703, 252, 125, 23);
		add(btnViewInvoice);
		
		if (p.getGender().equals("male")) { // Sets the gender button
			maleRadioButton.setSelected(true);
			gender = "male";
		}
		else {
			femaleRadioButton.setSelected(true);
			gender = "female";
		}
		
	     final Future future = MyThreadPool.submit(new Runnable() {
	            public void run() {
	            	
	                getTreatmentRecords(treatmentRows);
	            }});
	     final Future future2 = MyThreadPool.submit(new Runnable() {
	    	 	public void run(){
	    	 		
	    	 		generateChart();
	    	 	}});
	}
	

	/**
	 * Used to create an array of treatment records
	 *  given the row numbers of the 
	 *  treatment record data
	 * @param rowNumbers The row numbers containing the treatment record data needed
	
	 * @return An array of treatment records  */
	private TreatmentRecord[] getTreatmentRecords(int[] rowNumbers){
		
		treatmentArray = new TreatmentRecord[rowNumbers.length]; // $codepro.audit.disable variableShouldBeFinal
		final String[][] rawData = new String[rowNumbers.length][];
		for (int i = 0; i < rowNumbers.length; i++){
			rawData[i] = myDataManager.getDataAtRow(
						GlobalVars.TREATMENT_RECORD_SHEET,
						1,
						16, 
						rowNumbers[i]
						 );
			treatmentArray[i] = new TreatmentRecord(rawData[i]); 
			}
			for (int j = 0; j < treatmentArray.length; j++) { 
				treatmentArrayList.add(fillTreatmentArray(treatmentArray[j])); 
			}
			treatmentList = new JList(treatmentArrayList.toArray());
			treatmentList.addMouseListener(new MouseAdapter() { // Adds support for double clicking on a treatment record
				public void mouseClicked(MouseEvent e) {
					if (e.getClickCount() == 2) {
						final int index = treatmentList.locationToIndex(e.getPoint());
						treatRecord = new CreateTreatmentRecord(myDataManager, treatmentArray[index], treatmentRows[index], null); // pass in treatmentRows to identify row editing
					}
				}
			});
			scrollPane_1.setViewportView(treatmentList);
		
		return treatmentArray;
	}
	
	/**
	 * Displays the Date of each treatment record
	 * @param record a treatment record object
	
	 * @return the Data of the appointment in the treatment record */
	  public String fillTreatmentArray(TreatmentRecord record) {
		  return record.getCreationDate();
	  }
	  
	  /**
	   * Save the data to the database
	   */
	  public void savePressed() {
		final Person editPatient = new Patient(txtFirstName.getText(), txtLastName.getText(), 
										 gender, txtAge.getText(), txtSocialNum.getText(), 
										 txtPhoneNum.getText(), txtAddress.getText(), 
										 txtEmail.getText(), txtAllergies.getText(), 
										 txtPharmacy.getText(), txtInsurance.getText(), 
										 txtUserID.getText());
		myDataManager.setData(GlobalVars.PATIENT_SHEET, editPatient, null, patientRowNum[0]); // patientRowNum[0] is the patientRowNumber
	  }
	
	private void generateChart(){
		final JFreeChart chart = createChart();  
		 chartPanel = new ChartPanel(chart);
		chartPanel.setBounds(519, 340, 484, 250);
		add(chartPanel);
		chartPanel.revalidate();
		chartPanel.repaint();
		return;
	 }
	/**
	 * Method createWindow.
	 * @param myDataManager DataManager
	 * @param p Patient
	 * @return JFrame
	 */
	public static JFrame createWindow(DataManager myDataManager, Patient p) {
		Frame = new JFrame();
		Frame.setSize(1032, 668);
	
		Frame.getContentPane().add(new PatientInformationPanel(myDataManager, p));
		
		Frame.setVisible(true);
		Frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		return Frame;
		}
	
	/**
	 * create a chart based on treated date and weight of the patient
	
	
	
	 * @return chart */
	 private JFreeChart createChart() {
		 final int[] rowNum = myDataManager.getRowNumbers(GlobalVars.TREATMENT_RECORD_SHEET, 1, person1.getLoginName());
		 final String[] dateList = myDataManager.getDataAtCol(GlobalVars.TREATMENT_RECORD_SHEET, "Appointment Date", "Appointment Date");
		 final String[] weightList = myDataManager.getDataAtCol(GlobalVars.TREATMENT_RECORD_SHEET, "Weight", "Weight");
		 
		 //specified patient's treated date and weight list
		 final String[] pDateList = new String[rowNum.length];
		 final String[] pWeightList = new String[rowNum.length];
		 
		 final TimeSeries series = new TimeSeries("Average Weight");
		 
		 for(int i=0; i < rowNum.length; i++){
			 DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
			 
			 pDateList[i] = dateList[rowNum[i] - 2];
			 pWeightList[i] = weightList[rowNum[i] - 2];
			 
			 try{
				 Date dataDate = df.parse(pDateList[i]);	//parse string to date
				 int weight = Integer.parseInt(pWeightList[i]);
				 series.add(new Day(dataDate), weight);	//Set plot data
			 }
			 catch (java.text.ParseException e) {
				e.printStackTrace();
			 }
			 
		 }
		 
		 final TimeSeriesCollection dataset = new TimeSeriesCollection();
		 dataset.addSeries(series);
         
		 final JFreeChart chart = ChartFactory.createTimeSeriesChart(null, "Date", "Weight", dataset, true, true, false);
		 chart.setBackgroundPaint(new GradientPaint(0, 0, Color.white, 1000, 0, Color.blue));
		 
		 final XYPlot plot = (XYPlot) chart.getPlot();
		 
		 //set format of axis
		 final DateAxis axis = (DateAxis) plot.getDomainAxis();
		 axis.setAutoRange(true);
         axis.setDateFormatOverride(new SimpleDateFormat("MM/dd/yyyy"));
         
		  return chart;
	   } 
}
